/**
 * 
 */
package tp8.tsh.cli;

import java.io.IOException;
import java.io.InputStream;

import jline.ConsoleReader;
import jline.Terminal;

/**
 * @author tpana
 *
 */
public class TSHInput {

	Terminal terminal;
	
//	private ConsoleReader consoleReader;
	
	private InputStream in;
	
	/**
	 * @return the in
	 */
	public synchronized InputStream getIn() {
		return in;
	}

	/**
	 * @param in the in to set
	 */
	public synchronized void setIn(InputStream in) {
		this.in = in;
		try {
			terminal = Terminal.setupTerminal();
			terminal.enableEcho();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public String readLine() {
		StringBuilder strBuilder = new StringBuilder();
		boolean readNext = true;
		int readChar = 0;
		while (readNext) {
			readChar = read();
			// Check if control char
			if (readChar == 10) {
				readNext = false;
			} else {
				strBuilder.append((char) readChar);
			}
		}
		
		return strBuilder.toString();
	}
	
	public int read() {
		try {
//			return in.read();
			return terminal.readCharacter(in);
		} catch (IOException e) {
			return 0;
		}
	}
}
